<template>
  <PageContainer>
    <view class="container relative">
      <Header
        title="意向供需收集"
        v-model="headerHeight"
        :is-box-shadow="false"
        :is-custom-back="true"
        @go-back="handleGoBack"
      />
      <!-- 预设字段列表 -->
      <view class="pa-16 preset-schemas" :style="{ top: headerHeight + 'px' }">
        <view class="default-color fz-14 font-bold mb-16"><text>设置意向收集表</text></view>
        <view class="disFlx flex-wrap mb-16" style="gap: 24rpx">
          <template v-for="(schema, index) in presetSchemas" :key="index">
            <view
              class="px-12 h-32 disFlxAC br-4 relative"
              :style="{
                border: '1px solid',
                borderColor: hasChecked(schema.field) ? '#2878ff' : '#EBEDF0',
                maxWidth: '400rpx',
              }"
              @click="handleSelectFields(schema)"
            >
              <text class="flex-1 ov-1">{{ schema.label }}</text>
              <view
                v-if="hasChecked(schema.field)"
                class="absolute right-0 bottom-0 w-14 h-14 schema-tag"
              >
                <text class="ali-icon fz-8" style="color: #fff">&#xe69f;</text>
              </view>
            </view>
          </template>
        </view>
        <view class="disFlxAC flexEnd">
          <text class="fz-12 mr-12" style="color: #969799">没找到合适的？</text>
          <TButton
            text="添加字段"
            type="none"
            :icon="'\ue61f'"
            custom-class="borderBtn br-16 h-32 linh-32"
            :custom-style="{
              border: '1px solid #2878ff',
              color: '#2878ff',
              backgroundColor: 'transparent',
              width: '216rpx',
            }"
            @click.stop="createFormItem"
          />
        </view>
      </view>
      <view class="pa-16">
        <template v-for="(item, index) in formItemList" :key="index">
          <view
            class="bg-white br-8 disFlx mb-12"
            style="border: 1px solid #fff; box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.4)"
          >
            <view
              class="w-32 flex-shrink-0 disFlxCC overflow-hidden"
              style="border-top-left-radius: 16rpx; height: initial"
            >
              <view
                class="w-full h-32 disFlxCC default-color fz-14 font-bold flex-shrink-0"
                style="background-color: #dcdee0"
              >
                <text>{{ index + 1 }}</text>
              </view>
              <view
                class="w-full h-full flex-1 disFlxCC fz-12 fontTC"
                style="color: #969799; background-color: #ebedf0; border-bottom-left-radius: 16rpx"
              >
                <text>{{ getFormItemTypeText(item.component) }}</text>
              </view>
            </view>
            <view class="flex-1 pa-16">
              <view class="disFlxJS">
                <text class="fz-14 default-color font-bold flex-1 ov-1">{{ item.label }}</text>
                <view class="disFlxJC" @click="handleRequired(item)">
                  <text v-if="item.required" class="ali-icon fz-20" style="color: #2878ff">
                    &#xe693;
                  </text>
                  <text v-else class="ali-icon fz-20" style="color: #999996">&#xe690;</text>
                  <text class="fz-14 default-color ml-8">必填</text>
                </view>
              </view>
              <view class="my-12 h-1" style="background-color: #ebedf0"></view>
              <view class="disFlxJS">
                <view class="flex-1 disFlxAC" style="gap: 24rpx">
                  <view v-if="index !== 0" class="action-button" @click="handleAction('up', item)">
                    <text>上移</text>
                  </view>
                  <view
                    v-if="index !== formItemList.length - 1"
                    class="action-button"
                    @click="handleAction('down', item)"
                  >
                    <text>下移</text>
                  </view>
                  <view class="action-button" @click="handleAction('copy', item)">
                    <text>复制</text>
                  </view>
                  <view class="action-button" @click="handleAction('delete', item)">
                    <text>删除</text>
                  </view>
                </view>
                <view class="action-button" @click="handleAction('edit', item)">
                  <text>编辑</text>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
      <ScrollTop :bottom="220" />
      <TButtonGroup show-background>
        <TButton
          class="gutter-btn"
          text="上一步"
          type="none"
          custom-class="borderBtn"
          @click.stop="handlePreviousStep"
        />
        <TButton class="gutter-btn" text="发布供需" type="primary" @click.stop="handleSubmit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* businessOpportunitiesFormCreate 供需的表单创建 */
  import { customFormItemTypeList } from '@/api';
  import type { CustomFormItemTypeListResult } from '@/api/indexTypes';
  import type { ComponentProps, FormSchema } from '@/components/Form';
  import type { ComponentType, Localdata } from '@/components/Form/types';
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import { navigateBack, navigateTo, onLoad, redirectTo } from '@/router';
  import type { BusinessOpportunitiesFormCreate } from '@/router/types/modules';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { cloneDeep, isArray, isBoolean, isString, max } from 'lodash-es';
  import ScrollTop from '@/components/ScrollTop/index.vue';
  import { ref } from 'vue';
  import {
    boCustomFieldLibraryList,
    getBoFormItemGetById,
    publishBo,
    submitBoFormItemAddOrUpdate,
  } from '@/api/businessOpportunities';
  import { Toast } from '@/utils';
  import type { BoFormAddOrUpdateItmeData } from '@/api/businessOpportunities/type';
  import { IsRequired } from '@/enums/formEnum';
  import { BoStatusEnum, ReleaseTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import { localDataMapping } from '@/components/Form/hooks/useForm';

  type ToolbarType = 'edit' | 'copy' | 'up' | 'down' | 'delete';

  const headerHeight = ref(87);

  /** 预设字段列表 */
  const presetSchemas = ref<FormSchema[]>([]);
  const hasChecked = (field: string) => {
    return formItemList.value.find((v) => v.dataType === field);
  };

  /** 选择预设字段 */
  function handleSelectFields(schema: FormSchema) {
    if (hasChecked(schema.field)) {
      const item = formItemList.value.find((v) => v.dataType === schema.field);
      handleAction('delete', cloneDeep(item) as FormSchema);
    } else {
      createFormItem({
        field: '',
        label: schema.label,
        component: schema.component,
        dataType: schema.field,
        required: schema.required,
        componentProps: {
          ...schema.componentProps,
        },
      });
    }
  }

  /** 表单项列表 */
  const formItemList = ref<FormSchema[]>([]);

  const formItemTypeList = ref<CustomFormItemTypeListResult[]>([]);

  /** 获取表单组件对应的文字名称 */
  const getFormItemTypeText = (type: ComponentType) =>
    formItemTypeList.value.find((item) => item.type === type)?.name;

  const routeOptions = ref<BusinessOpportunitiesFormCreate>();
  onLoad<'businessOpportunitiesFormCreate'>(async (op) => {
    routeOptions.value = op;
    customFormItemTypeList().then((res) => (formItemTypeList.value = res));
    boCustomFieldLibraryList(op.id).then((res) => {
      presetSchemas.value = res.map((v) => ({
        field: v.id.toString(),
        label: v.name,
        component: v.itemType,
        required: v.isRequired === IsRequired.REQUIRED,
        componentProps: {
          placeholder: v.value,
        },
      }));
    });
    const res = await getBoFormItemGetById(op.id, op.releaseType);
    const list: FormSchema[] = [];
    res.formItemList.forEach((item) => {
      const id = item.id.toString();
      const data: FormSchema = {
        field: id,
        label: item.showName,
        component: item.itemType,
        defaultValue: item.itemDefault,
        required: item.isRequired === IsRequired.REQUIRED,
        dataType: item.fieldLibraryId?.toString(),
        dynamicDisabled: item.disabled,
        componentProps: {
          placeholder: item.value,
          localdata: localDataMapping(item.customFormItemAnswerList, {
            label: 'words',
            value: 'id',
          }),
        },
      };
      list.push(data);
    });

    formItemList.value = list as any;
  });

  /** 设置必填 */
  function handleRequired(item: FormSchema) {
    item.required = isBoolean(item.required) ? !item.required : true;
  }

  /** 表单项工具栏操作 */
  function handleAction(type: ToolbarType, schema: FormSchema) {
    switch (type) {
      case 'edit':
        createFormItem(schema, true);
        break;
      case 'copy':
        const data = cloneDeep(schema);
        data.field = '';
        createFormItem(schema);
        break;
      case 'delete':
        uni.showModal({
          title: '删除',
          content: '确定要删除当前项吗?',
          confirmText: '立即删除',
          confirmColor: '#EA5E0E',
          cancelText: '取消',
          cancelColor: '#999996',
          success: ({ confirm }) => {
            if (confirm) {
              const index = formItemList.value.findIndex((item) => item.field === schema.field);
              if (index !== -1) {
                formItemList.value.splice(index, 1);
              }
            }
          },
        });
        break;
      case 'up':
      case 'down':
        const index = formItemList.value.findIndex((item) => item.field === schema.field);
        if (type === 'up' && index === 0) return;
        if (type === 'down' && index === formItemList.value.length - 1) return;
        const newSchema = formItemList.value.splice(index, 1)[0];
        formItemList.value.splice(index + (type === 'up' ? -1 : 1), 0, newSchema);
        break;
    }
  }

  /** 创建/编辑表单项 */
  function createFormItem(item?: FormSchema, isEdit?: boolean) {
    navigateTo({
      name: 'createFormItem',
      options: {
        item,
        success: (data) => {
          const d = cloneDeep(data) as FormSchema;

          if (d.dataType) {
            const p = presetSchemas.value.find((v) => v.field === d.dataType);
            if (p) {
              p.label = d.label;
              p.componentProps = { ...d.componentProps } as any;
            }
          }

          if (item && isEdit) {
            const index = formItemList.value.findIndex((item) => item.field === data.field);
            formItemList.value[index] = d as any;
          } else {
            formItemList.value.push(d as any);
          }
        },
      },
    });
  }

  const handleGoBack = () => {
    redirectTo({
      name: 'releaseBusinessOpportunities',
      options: {
        id: routeOptions.value?.id,
        releaseType: routeOptions.value?.releaseType!,
      },
    });
  };

  const saveFormData = async () => {
    if (!formItemList.value.length) {
      Toast('请添加字段');
      return Promise.reject('请添加字段');
    }

    const list = formItemList.value;
    const data: BoFormAddOrUpdateItmeData = {
      customFromId: routeOptions.value?.id as number,
      customFormItemList: [],
    };
    list.forEach((v) => {
      const id = Number.isNaN(v.field) ? null : Number(v.field);
      const label = v.label as string;
      const componentProps = v.componentProps as ComponentProps;
      const localdata =
        componentProps && isArray(componentProps?.localdata)
          ? (componentProps?.localdata as Localdata[])
          : [];
      data.customFormItemList.push({
        id: id,
        name: v.field,
        showName: label,
        itemType: v.component as ComponentType,
        isRequired: v.required ? IsRequired.REQUIRED : IsRequired.NOTREQUIRED,
        value: componentProps?.placeholder as string,
        fieldLibraryId: v.dataType,
        customFormItemAnswerDtoList: localdata.map((v) => {
          return {
            id: isString(v.value) ? null : v.value,
            words: v.text,
          };
        }),
      });
    });
    return await submitBoFormItemAddOrUpdate(data, routeOptions.value?.releaseType);
  };

  /** 上一步 */
  const handlePreviousStep = async () => {
    await saveFormData();
    redirectTo({
      name: 'releaseBusinessOpportunities',
      options: {
        id: routeOptions.value!.id,
        releaseType: routeOptions.value!.releaseType,
      },
    });
  };
  /** 提交发布 */
  const handleSubmit = async () => {
    await saveFormData();
    const res = await publishBo(routeOptions.value?.id!, routeOptions.value?.releaseType!);
    uni.$emit(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
    if (
      routeOptions.value?.releaseType === ReleaseTypeEnum.member &&
      res.boStatus !== BoStatusEnum.Active
    ) {
      redirectTo({
        name: 'releaseBoResult',
        options: {
          id: res.id!,
          reviewRecordId: res.reviewRecordId!,
        },
      });
    } else {
      Toast({
        title: '发布成功',
        icon: 'success',
        success: () => {
          navigateBack();
        },
      });
    }
  };
</script>

<style lang="scss" scoped>
  $color: #2878ff;
  .preset-schemas {
    position: sticky;
    background-color: #fff;
  }
  .schema-tag {
    background: linear-gradient(-45deg, $color, $color 50%, transparent 50%, transparent 100%);
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
  }

  .add-button {
    color: $color;
    width: 216rpx;
    border: 1px solid #2878ff;
  }

  .action-button {
    border: 1px solid #c8cacc;
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
    color: #333;
    font-size: 24rpx;
  }
</style>
